<?php

namespace app\api\controller;

use think\Db;

class Weixin extends BaseController
{
    //微信登录、获取用户信息
    public function login()
    {
        $code = input('post.code', '');
        $token = input('post.token', '');
        $admin = input('post.admin', '');
        $admin = explode('_', $admin);
        $admin_id = $admin[0];
        $admin_type = count($admin) > 1 ? intval($admin[1]) : 1;
        if (!$code) {
            return error('缺少参数：code');
        }
        $flag = true;
        // 快速登录（针对老用户快速登录，3天更新一次用户信息）
        if($token){
            $user_info = Db::name('user')->find($token);
            if($user_info&&$user_info['last_time']>time()-86400*3){
                $flag = false;
                $token = $user_info['id'];
                $data = Db::name('gang')->find($user_info['gang_id']);
                $u = ['id' => strval($user_info['id']), 'name' => strval($user_info['name']), 'avatar' => strval($user_info['avatar']), 'phone' => strval($user_info['phone']), 'gang_id' => strval($data['id']), 'gang_name' => strval($data['name']), 'gang_role' => intval($user_info['gang_role']), 'shop_id' => strval($user_info['shop_id']), 'gzh_openid' => strval($user_info['gzh_openid'])];
            }
        }
        if ($flag) {
            // 更新用户信息
            $surl = sprintf('https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code&lang=zh_CN', config('wx_appid'), config('wx_secretkey'), $code);
            $result = httpGet($surl);
            $result = json_decode($result);
            if ($result->openid) {
                //用户信息 先解密
                $encrypted_data = input('post.encryptedData', '');
                $iv = input('post.iv', '');
                if (!$encrypted_data) {
                    return error('缺少参数：encryptedData');
                }
                if (!$iv) {
                    return error('缺少参数：iv');
                }
                $wxs = new \wx\WeixinService();
                $error = $wxs->decryptData($result->session_key, $encrypted_data, $iv, $user_data);
                if ($error) {
                    return error('获取用户信息失败！'.json_encode($error));
                }
                //性别 0：未知、1：男、2：女
                $row = ['openid' => $result->openid, 'unionid' => $user_data['unionId'],  'session_key' => $result->session_key,  'name' => $user_data['nickName'], 'sex' => intval($user_data['gender']), 'city' => $user_data['city'], 'province' => $user_data['province'], 'country' => $user_data['country'], 'avatar' => $user_data['avatarUrl'], 'last_ip' => getRemoteIp(), 'last_time' => time()];
                $user_info = Db::name('user')->where(['openid' => $result->openid])->find();
                // 新增用户数统计
                if (!$user_info) {
                    $row['ct'] = time();
                    $bt = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                    $et = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                    $total_info = Db::name('total_data')->where(['ct' => [['gte', $bt], ['lte', $et]]])->find();
                    if ($total_info) {
                        Db::name('total_data')->where('id', $total_info['id'])->update(['user_num' => intval($total_info['user_num']) + 1]);
                    } else {
                        Db::name('total_data')->insert(['ct' => time(), 'user_num' => 1]);
                    }
                }
                Db::name('user')->where(['openid' => $result->openid])->update($row, ['upsert' => true]);

                $user_info = Db::name('user')->where(['openid' => $result->openid])->find();
                $token = $user_info['id'];
                $data = Db::name('gang')->find($user_info['gang_id']);
                $u = ['id' => strval($user_info['id']), 'name' => strval($user_info['name']), 'avatar' => strval($user_info['avatar']), 'phone' => strval($user_info['phone']), 'gang_id' => strval($data['id']), 'gang_name' => strval($data['name']), 'gang_role' => intval($user_info['gang_role']), 'shop_id' => strval($user_info['shop_id']), 'gzh_openid' => strval($user_info['gzh_openid'])];
            }
        }
        if ($u) {
            cache('api_user_info_'.$u['id'], null);
            if (24 == strlen($admin_id) && 1 == $admin_type) {
                // 管理员绑定微信(提现账号绑定)
                $admin_info = Db::name('admin')->find($admin_id);
                if ($admin_info) {
                    if ($admin_info['openid'] != $result->openid) {
                        Db::name('admin')->where('id', $admin_id)->update(['openid' => $result->openid, 'unionid' => $user_data['unionId'], 'avatar' => $user_info['avatar'], 'nickname' => $user_info['name']]);
                        Db::name('user')->where('id', $token)->update(['phone' => $admin_info['phone'], 'admin_id' => $admin_info['id']]);
                    }
                    cache('admin_wx_login_'.$admin_id, ['ct' => time(), 'phone' => $admin_info['phone'], 'admin_id' => $admin_id], 10);
                }
            } elseif ($admin_id && $user_info['phone'] && 2 == $admin_type) {
                // 后台登录
                $admin_info = Db::name('admin')->where(['phone' => $user_info['phone']])->find();
                if ($admin_info) {
                    if ($admin_info['openid'] != $result->openid) {
                        Db::name('admin')->where('id', $admin_info['id'])->update(['openid' => $result->openid, 'avatar' => $user_info['avatar'], 'nickname' => $user_info['name']]);
                    }
                    cache('admin_wx_login_'.$admin_id, ['ct' => time(), 'phone' => $user_info['phone'], 'admin_id' => $admin_id], 10);
                }
            } elseif (24 == strlen($admin_id) && 3 == $admin_type) {
                // 供应商绑定微信公众号 接收推送消息 根据当前用户的unionid
                $admin_info = Db::name('admin')->find($admin_id);
                if ($admin_info) {
                    Db::name('admin')->where('id', $admin_id)->update(['gzh_openid' => $user_info['gzh_openid']]);
                    cache('admin_wx_login_'.$admin_id, ['ct' => time(), 'phone' => $admin_info['phone'], 'admin_id' => $admin_id, 'gzh_openid' => $user_info['gzh_openid']], 10);
                }
            }
            return success(['token' => $token, 'expires_in' => 7200, 'user_info' => $u]);
        }
        return error('参数错误');
    }

    //微信获取已有用户信息获取
    public function getUserInfo()
    {
        $user_id = input('post.user_id', '');
        if (!$user_id) {
            return error('获取用户信息失败！');
        } else {
            $user_info = Db::name('user')->where(['id' => $user_id])->find();
            if (!$user_info) {
                return error('获取用户信息失败！');
            } else {
                $data = Db::name('gang')->find($user_info['gang_id']);

                return success(['user_info' => ['name' => $user_info['name'], 'phone' => substr($user_info['phone'], 0, 3).'****'.substr($user_info['phone'], 7, 4), 'gang_id' => $data['id'], 'gang_name' => $data['name'], 'gang_role' => $user_info['gang_role']]]);
            }
        }
    }

    //根据产品ID生成二维码海报
    public function qrcode()
    {
        $user_info = session('user_info');
        $product_id = input('post.product_id', '');
        if (!$product_id || 24 != strlen($product_id)) {
            return error('缺少参数：产品ID');
        }
        $shop_id = input('post.shop_id', '');
        $img_src = input('post.img', '');
        if (!$img_src) {
            return error('缺少参数：图片地址');
        }
        if (!$shop_id) {
            $shop_info = Db::name('shop')->where(['user_id' => $user_info['id']])->find();
            $shop_id = $shop_info['id'];
        } else {
            $shop_info = Db::name('shop')->where(['id' => $shop_id])->find();
        }
        if (!$shop_info) {
            return error('未找到该店！');
        }
        // 去掉判断 可以推小店以外的商品
        // $shop_product = Db::name('shop_product')->where(['shop_id' => $shop_info['id'], 'product_id' => $product_id])->find();
        // if (!$shop_product) {
        //     return error('该店里未找到此商品！');
        // }
        $product_info = Db::name('product')->field('name')->find($product_id);
        $title = $product_info['name'];
        $avatar = $user_info['avatar'];

        //根据用户ID 找用户头像 然后用户头像 产品二维码 产品图3个生成一个图
        $path = 'pages/productDetails/productDetails?shop_id='.$shop_id.'&product_id='.$product_id;
        $base_path = ROOT_PATH.'public/qrcode/';
        //海报地址
        $poster_path = $base_path.'poster_'.$shop_id.'_'.$product_id.'.jpg';
        //海报基础图
        $dst_path = $base_path.'/poster_base/poster_'.mt_rand(1, 3).'.jpg';
        //输出二维码与头像的合成图片
        $qr_img = $base_path.'cache/qrcode_avatar_'.$product_id.'_'.$user_info['id'].'.png';
        if (!file_exists($qr_img)) {
            //二维码地址
            $qr = $base_path.'cache/'.$shop_id.'_'.$product_id.'.png';
            $qr_width = 300;
            if (!file_exists($qr)) {
                $wxs = new \wx\WeixinService();
                // 因为参数超过32位 所以不能使用批量生成方法
                $result = $wxs->getQrCode($path, $qr_width);
                file_put_contents($qr, $result);
            }
            if (false !== strpos($avatar, 'http')) {
                $avatar_qr_width = 134;
                //输出头像的缓存图片
                $avatar_img = $base_path.'cache/avatar_'.$user_info['id'].'.png';
                if (!file_exists($avatar_img)) {
                    download($avatar, $avatar_img);
                    $image = \think\Image::open($avatar_img);
                    $image->thumb($avatar_qr_width, $avatar_qr_width)->save($avatar_img);
                    $avatar = getCircleAvatar($avatar_img, $avatar_qr_width, $avatar_qr_width);
                }

                $qr = imagecreatefrompng($qr);
                $avatar = imagecreatefrompng($avatar_img);
                $from_width = ($qr_width - $avatar_qr_width) / 2 - 1;
                //重新组合图片并调整大小
                imagecopyresampled($qr, $avatar, $from_width, $from_width, 0, 0, $avatar_qr_width, $avatar_qr_width, $avatar_qr_width, $avatar_qr_width);
                //定义白色为透明色
                $c = imagecolorallocate($qr, 255, 255, 255);
                imagecolortransparent($qr, $c);
            }
            imagepng($qr, $qr_img);
        }
        //创建图片的实例
        $dst = imagecreatefromstring(file_get_contents($dst_path));
        $src = imagecreatefromstring(file_get_contents($qr_img));
        list($dst_w, $dst_h) = getimagesize($dst_path);
        list($src_w, $src_h) = getimagesize($qr_img);
        //将覆盖图复制到目标图片上，最后个参数100是设置透明度（100是不透明），这里实现不透明效果
        imagecopymerge($dst, $src, ($dst_w - $src_w) / 2, $dst_h - 480, 0, 0, $src_w, $src_h, 100);
        //合成海报产品图部分
        $product_src = imagecreatefromstring(file_get_contents($img_src));
        list($product_src_w, $product_src_h) = getimagesize($img_src);
        imagecopymerge($dst, $product_src, ($dst_w - 640) / 2, 35, 0, 0, 640, 640, 100);

        // putenv('GDFONTPATH='.realpath('.')); //imagettftext不起作用的解决办法(本地windows环境有这个bug)
        //计算title长度 显示居中 过长显示2行
        $len = getShowLen($title);
        if ($len > 14) {
            $title1 = subString($title, 14);
        } else {
            $title1 = $title;
        }
        if ($len >= 14) {
            $title = str_replace($title1, '', $title);
            $title2 = subString($title, 14);
        }
        $col = imagecolorallocatealpha($dst, 51, 51, 51, 0);
        imagettftext($dst, 25, 0, ($dst_w - 14 * 33) / 2, $len > 14?700:743, $col, 'my.TTF', $title1);
        if ($title2) {
            imagettftext($dst, 25, 0, ($dst_w - getShowLen($title2) * 33) / 2, 740, $col, 'my.TTF', $title2);
        }

        imagejpeg($dst, $poster_path);

        //最后删除二维码与头像的合成图片 释放资源
        // @unlink($qr_img);
        imagedestroy($dst);
        imagedestroy($src);

        return success(config('file_domain').'qrcode/poster_'.$shop_id.'_'.$product_id.'.jpg');
    }

    //根据user_id生成小店二维码海报
    public function shopQrcode()
    {
        $user_info = session('user_info');
        $base_path = ROOT_PATH.'public/qrcode/';
        //海报地址
        $poster_path = $base_path.'poster_shop_'.$user_info['id'].'.jpg';
        //海报基础图
        $dst_path = $base_path.'/poster_base/shop_bg.jpg';
        //输出二维码与头像的合成图片
        $qr_img = $base_path.'cache/qrcode_shop_'.$user_info['id'].'.png';
        $avatar = $user_info['avatar'];
        if (!file_exists($qr_img)) {
            $path = 'pages/user/xiaodian';
            //小程序二维码地址
            $qr = $base_path.'cache/shop_'.$user_info['id'].'.png';
            $qr_width = 300;
            // 加个大小判断 如果生成的图是失败的  大小小于1KB
            $size = filesize($qr) / 1024;
            if (!file_exists($qr) || $size < 1) {
                $wxs = new \wx\WeixinService();
                $result = $wxs->getQrCodeUnlimit($path, $qr_width, $user_info['id'], true);
                file_put_contents($qr, $result);
            }
            if (false !== strpos($avatar, 'http')) {
                $avatar_qr_width = 132;
                //输出头像的缓存图片
                $avatar_img = $base_path.'cache/avatar_'.$user_info['id'].'.png';
                if (!file_exists($avatar_img)) {
                    download($avatar, $avatar_img);
                    $image = \think\Image::open($avatar_img);
                    $image->thumb($avatar_qr_width, $avatar_qr_width)->save($avatar_img);
                    $avatar = getCircleAvatar($avatar_img, $avatar_qr_width, $avatar_qr_width);
                }

                $qr = imagecreatefrompng($qr);
                $avatar = imagecreatefrompng($avatar_img);
                $from_width = ($qr_width - $avatar_qr_width) / 2 - 1;
                //重新组合图片并调整大小
                imagecopyresampled($qr, $avatar, $from_width, $from_width, 0, 0, $avatar_qr_width, $avatar_qr_width, $avatar_qr_width, $avatar_qr_width);
                //定义白色为透明色
                $c = imagecolorallocate($qr, 255, 255, 255);
                imagecolortransparent($qr, $c);
            }
            imagepng($qr, $qr_img);
        }

        //创建图片的实例
        $dst = imagecreatefromstring(file_get_contents($dst_path));
        $src = imagecreatefromstring(file_get_contents($qr_img));
        list($dst_w, $dst_h) = getimagesize($dst_path);
        list($src_w, $src_h) = getimagesize($qr_img);
        //将覆盖图复制到目标图片上，最后个参数100是设置透明度（100是不透明），这里实现不透明效果
        imagecopymerge($dst, $src, ($dst_w - $src_w) / 2, 350, 0, 0, $src_w, $src_h, 100);

        // putenv('GDFONTPATH='.realpath('.')); //imagettftext不起作用的解决办法(本地windows环境有这个bug)
        $len = mb_strlen($user_info['name'], 'utf-8');
        $col = imagecolorallocatealpha($dst, 51, 51, 51, 0);
        imagettftext($dst, 28, 0, ($dst_w - $len * 34) / 2, 810, $col, 'my.TTF', $user_info['name']);
        $col = imagecolorallocatealpha($dst, 16, 210, 121, 0);
        imagettftext($dst, 21, 0, ($dst_w - 7 * 28) / 2, 860, $col, 'my.TTF', '的羽毛球特卖店');

        imagejpeg($dst, $poster_path);

        //最后删除二维码与头像的合成图片 释放资源
        // @unlink($qr_img);
        imagedestroy($dst);
        imagedestroy($src);

        return success(config('file_domain').'qrcode/poster_shop_'.$user_info['id'].'.jpg');
    }
}
